﻿using CefSharp.DevTools.CSS;

namespace Web_rongmeiti_sys.PublishToRongMeiTi
{
    /// <summary>
    /// 身份cookie ,保存，获取
    /// </summary>
    /// 创建时间：2023-5-26 16:47:21。作者：王浩力
    public class AuthCookieHelpter
    {
        /// <summary>
        /// 身份cookie。  缓存key
        /// </summary>
        public const string CACHE_COOKIE1 = "CookiesAll_data";

        /// <summary>
        /// cookie缓存时长，单位，小时
        /// </summary>
        const int liveHours = 240;

        ///// <summary>
        ///// cookie保存的文件
        ///// </summary>
        //private const string cookieSaveFile = "cookie_value.txt";

        /// <summary>
        /// 保存身份验证的cookie的值， 存为缓存+本地磁盘文件
        /// </summary>
        /// <param name="value"></param>
        public static void SaveCookie(string account, string cookieSb)
        {
            string cacheKey = account + "700";

            //string cookieAll = $".AspNetCore.Cookies=chunks-2;" + LoginHandler.cookieSb.ToString();
            string cookieAll = $".AspNetCore.Cookies=chunks-2;" + cookieSb;

            System.Runtime.Caching.MemoryCache.Default.Set(cacheKey, cookieAll, DateTime.Now.AddHours(liveHours));
            string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "identity_cookie");
            if (!System.IO.Directory.Exists(dir))
            {
                System.IO.Directory.CreateDirectory(dir);
            }
            string filePath = Path.Combine(dir, $"cookieValue_{account}.txt");
            File.WriteAllText(filePath, cookieAll);
        }

        /// <summary>
        /// 获取身份验证的cookie
        /// </summary>
        /// <returns></returns>
        /// 创建时间：2023-5-26 16:59:09。作者：王浩力
        public static string GetIdentityCookie(string account)
        {
            string cacheKey = account + "700";
            string cookieValue = System.Runtime.Caching.MemoryCache.Default.Get(cacheKey)?.ToString();
            if (cookieValue!=null && cookieValue.Length>0)
            {
                LogHelpter.AddLog("GetIdentityCookie命中缓存，account="+ account,null, "GetIdentityCookie");
            }
            if (string.IsNullOrWhiteSpace(cookieValue))
            {
                string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "identity_cookie");
                string filePath = Path.Combine(dir, $"cookieValue_{account}.txt");
                if (!System.IO.File.Exists(filePath))
                {
                    return null;
                }
                cookieValue = File.ReadAllText(filePath);
                if (cookieValue.Length > 0)
                {
                    System.Runtime.Caching.MemoryCache.Default.Set(cacheKey, cookieValue, DateTime.Now.AddHours(liveHours));
                }
            }
            return cookieValue;
        }


    }
}
